package de.koo.grum.test.integration

import de.koo.grum.domain.Address;
import de.koo.grum.domain.ContactData;
import de.koo.grum.domain.User;
import grails.test.*

class ContactDataTests extends GrailsUnitTestCase {
    def newIds=[]
    def newUserIds=[]

    protected void setUp() {
        super.setUp()

        newIds=[]
        newUserIds=[]

        def user = new User(username:"lsimpson",password:"secret",firstname:"Lisa",lastname:"Simpson")
        Address address = new Address(city:"Springfield",street:"strasse 1",zipcode:"10001")
        user.address=address

        address.save(flush:true)
        user.save(flush:true)

        newUserIds <<= user.id

    }

    protected void tearDown() {
        super.tearDown()

        newIds.each() { newId ->
            def contactData=ContactData.get(newId)
            if (contactData!=null) {
                contactData.delete(flush:true)
            }
        }

        newUserIds.each() { newId ->
            def user=User.get(newId)
            if (user!=null) {
                def address=user.address
                address.delete(flush:true)
                user.delete(flush:true)
            }
        }
    }

    void testSearch() {
        def contactDataList
        def searchString="lsim"
/*

        def c = ContactData.createCriteria()
        contactDataList = c.list {
            join 'user'
            or { like("data","%${searchString}%")
                like("type","%${searchString}%")
                user {
                    or { like("firstname","%${searchString}%")
                        like("lastname","%${searchString}%")
                    }
                }
            }
        }
*/
        contactDataList=ContactData.findAll("from ContactData as cd inner join cd.user as user \
                where user.firstname = ?", ['gero']
            )
        assert contactDataList.size() > 0
    }

    void testCreate() {
        def contactData = new ContactData(data:"lisa@simpsons.com",type:"email")
        contactData.user=User.get(newUserIds[0])
        def newId=0

        if(contactData.save(flush:true)) {
            assert contactData.errors.allErrors.size() == 0
            newId = contactData.id

            newIds <<= contactData.id
        }
        else {
            assert contactData.errors.allErrors.size() == 0
        }

        contactData=ContactData.get(newId)
        assert contactData != null
        assert contactData.data == "lisa@simpsons.com"
    }
}
